package com.neusoft.crm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neusoft.crm.entity.CommonResult;
import com.neusoft.crm.entity.Role;
import com.neusoft.crm.entity.Sysinfo;
import com.neusoft.crm.mapper.RolesMapper;
import com.neusoft.crm.mapper.SysinfoMapper;
import com.neusoft.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 东软集团
 * @since 2023-04-03
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RolesMapper, Role> implements IRoleService {
    @Autowired
    RolesMapper rolesMapper;

    @Autowired
    SysinfoMapper sysinfoMapper;

    @Override
    public CommonResult loadAll() {
        List<Role> lrs =  rolesMapper.selectList(null);
        CommonResult result = new CommonResult(lrs);
        if (lrs ==null || lrs.size() ==0){
            result.setNotFound();
        }
        return result;
    }

    @Override
    public CommonResult modRole(Role role) {

        int  i = rolesMapper.updateById(role);

        CommonResult  result =new CommonResult(i);

        if ( i < 1){
            result.setNotModified();
        }

        return result;
    }

    @Override
    public CommonResult addRole(Role role) {

        role.setRoleno(null);

        int i =  rolesMapper.insert(role);

        CommonResult result = new CommonResult(role.getRoleno());

        if (i <  1)result.setNotModified();

        return result;
    }

    @Override
    public CommonResult getSysByRoleno(String roleno) {
        List<String> lss =   sysinfoMapper.getSysByRoleno(roleno);
        CommonResult  result =new CommonResult(lss);
        if (lss ==null || lss.size() ==0)
            result.setNotFound();
        return result;
    }

    @Override
    @Transactional( propagation = Propagation.REQUIRED , rollbackFor = Exception.class)
    public CommonResult modSys(String roleno, String[] sysnos) {
//        根据roleno 把所有的sysno都删除
        int i = sysinfoMapper.delSysinfoByRoleno(roleno);
        if (i > 0)
            i = sysinfoMapper.batchInsert(roleno, sysnos);
//        批量插入

        CommonResult result = new CommonResult(i);
        if (i < 1)
            result.setNotModified();

        return result;
    }

    /**
     * 加载角色的系统功能子树信息，返回列表
     *
     * @param roleno
     * @return
     */
    @Override
    public CommonResult getSysListByRoleno(String roleno) {
        List<Sysinfo>  lss =   sysinfoMapper.getSysListByRoleno(  roleno);

        CommonResult  result =new CommonResult(lss);
        if ( lss ==null || lss.size() ==0)
            result.setNoutFound();
        return result;
    }


}
